package service;

import java.util.List;

import com.jfinal.aop.Aop;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import model.Role;
import model.User;
import model.UserRole;

public class UserRoleService extends BaseService {
	
	static UserService userService = Aop.get(UserService.class);
	static MenuService menuService = Aop.get(MenuService.class);
	
	public Ret save(String roles, Long userId) {
		
		UserRole.dao.deleteByUserId(userId);
		
		StringBuffer roleNames = new StringBuffer() ;
		if(StrKit.notBlank(roles)) {
			String[] roleArr = roles.split(",");
			for(String roleId : roleArr) {
				Role role = Role.dao.findById(roleId);
				if (null == role) {
					continue ;
				}
				
				UserRole userRole = new UserRole();
				userRole.set("userId",userId);
				userRole.set("roleId",roleId);
				userRole.save();
				
				roleNames.append(roleNames.length() > 0 ? "," : "").append(role.getName());
			}
			User user = new User();
			user.setRoleNames(roleNames.toString());
			user.setId(userId);
			user.update();
		}
		return Ret.ok();		
	}
	

	public List<Record> findUserToMenu(User user) {
		Long userId = user.getId() ;
		if (userId == User.ADMIN_ID) {
			return menuService.getAllMenu();
		}
		StringBuffer sBuffer = new StringBuffer("SELECT tm.* , tmp.name AS parentName FROM t_role_menu trm ");
		sBuffer.append(" LEFT JOIN  t_menu tm ON trm.menuId = tm.Id");
		sBuffer.append(" LEFT JOIN t_menu tmp ON tmp.id = tm.parentId ");
		sBuffer.append(" WHERE trm.roleId IN ("+ user.getRoleIds() +") " );
		sBuffer.append(" GROUP BY tm.id ORDER BY tmp.orderNum , tm.orderNum ");
		return Db.findByCache( "menuList" , user.getId() , sBuffer.toString());
	}

	public List<Record> findUserToRole(String userId) {
		List<Record> recordList=  Db.find("SELECT tr.id,tr.name FROM t_role tr "
				+ " LEFT JOIN t_user_role tur ON tr.`id`= tur.`roleId`"
				+ " WHERE tur.`userId` = ?", userId);
		return recordList;
	}
}
